package com.likou;

/**
 * Author: 陈桂明
 * Date: 2025/4/9 18:53
 * Description: q4
 */
public class q4 {
    public static void main(String[] args) {
        double medianSortedArrays = new q4().findMedianSortedArrays(new int[]{1, 3}, new int[]{2});
        System.out.println(medianSortedArrays);
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int p1 = 0;
        int p2 = 0;
        int sum = 0;
        int mark = 0;
        if ((m + n) % 2 != 0) {
            while (p1 != m && p2 != n) {
                int a = nums1[p1];
                int b = nums2[p2];
                if (mark == (m + n) / 2) {
                    return Math.min(a, b);
                }
                if (a >= b) {
                    p2++;
                } else {
                    p1++;
                }
                mark++;
            }

            if (p1 == m) {
                for (int i = p2; i < nums2.length; i++) {
                    if (mark == (m + n) / 2) {
                        return nums2[i];
                    }
                    mark++;
                }
            }
            if (p2 == n) {
                for (int i = p1; i < nums1.length; i++) {
                    if (mark == (m + n) / 2) {
                        return nums1[i];
                    }
                    mark++;
                }
            }
        } else {
            while (p1 != m && p2 != n) {
                int a = nums1[p1];
                int b = nums2[p2];
                if (mark == (m + n) / 2 || mark == (m + n) / 2 - 1) {
                    sum += Math.min(a, b);
                }
                if (a >= b) {
                    p2++;
                } else {
                    p1++;
                }
                mark++;
            }

            if (p1 == m) {
                for (int i = p2; i < nums2.length; i++) {
                    if (mark == (m + n) / 2 || mark == (m + n) / 2 - 1) {
                        sum += nums2[i];
                    }
                    mark++;
                }
            }
            if (p2 == n) {
                for (int i = p1; i < nums1.length; i++) {
                    if (mark == (m + n) / 2 || mark == (m + n) / 2 - 1) {
                        sum += nums1[i];
                    }
                    mark++;
                }
            }
        }
        return sum / 2.0;
    }
}
